import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { api } from '@/utils/request'
import type { LoginRequest, LoginResponse, UserInfo } from '@/types/auth'

export const useAuthStore = defineStore(
  'auth',
  () => {
    const token = ref<string>('')
    const userInfo = ref<UserInfo | null>(null)

    // 计算属性：是否已登录
    const isAuthenticated = computed(() => !!token.value)

    // 登录
    async function login(credentials: LoginRequest) {
      const response = await api.post<LoginResponse>('/auth/login', credentials)
      token.value = response.token
      userInfo.value = response.user
      return response
    }

    // 登出
    function logout() {
      token.value = ''
      userInfo.value = null
    }

    return {
      token,
      userInfo,
      isAuthenticated,
      login,
      logout,
    }
  },
  {
    persist: true,
  }
)
